//
//  MPNewsTableViewController.m
//  M800Project
//
//  Created by 姚宗超 on 14/11/10.
//  Copyright (c) 2014年 姚宗超. All rights reserved.
//

#import "MPNewsTableViewController.h"
#import "MPNetworkService.h"
#import "MPNewsTableCell.h"
#import "MPNewsTableItem.h"
#import "MPDeviceObject.h"
#import "KDCycleBannerView.h"
#import "MPNewsBannerItem.h"
#import "UIImage+Common.h"
#import "MPWebViewController.h"
#import "RDVTabBarController.h"
#import "MPWebViewController.h"

@interface MPNewsTableViewController () <KDCycleBannerViewDataource, KDCycleBannerViewDelegate>
@property (nonatomic, strong)KDCycleBannerView* bannerView;
@property (nonatomic, strong)NSMutableArray* bannerItemArray;
@property (nonatomic, assign)NSUInteger loadMorePageInt;

@end

@implementation MPNewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"资讯";
    [self.view addSubview:self.bannerView];
    
    self.tableView.showsInfiniteScrolling = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(@160.0f);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bannerView.mas_bottom);
        make.leading.trailing.bottom.mas_equalTo(self.view);
    }];
    
//    [self.view setNeedsLayout];
//    [self.view layoutIfNeeded];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.rdv_tabBarController.tabBarHidden = NO;

    [self createModel];
}

- (void)createModel
{
    // 取资讯列表
    self.loadMorePageInt = 1;
    [MPNetworkService fetchNewsWithInfoType:eMPInfoTypeP2P page:self.loadMorePageInt onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        
        [self.firstSectionObject.items removeAllObjects];
        [self.sections removeAllObjects];
        NSArray* infoArray = (NSArray *)info;
        for (NSDictionary* infoDic in infoArray) {
            MPNewsTableItem* item = [MPNewsTableItem itemWithInfoDic:infoDic];
            [self.firstSectionObject.items addObject:item];
        }
        [self.sections addObject:self.firstSectionObject];
        [self.tableView reloadData];
    }];
    
    // 获取滚动广告
    [MPNetworkService fetchAdvertiseWithInfoType:eMPInfoTypeP2P onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        [self.bannerItemArray removeAllObjects];
        NSArray* infoArray = (NSArray *)info;
        for (NSDictionary* infoDic in infoArray) {
            MPNewsBannerItem* item = [MPNewsBannerItem itemWithInfoDic:infoDic];
            [self.bannerItemArray addObject:item];
        }
        [self.bannerView reloadDataWithCompleteBlock:nil];
    }];
}

// 上拉加载
- (void)infiniteScrollingAction
{
    [MPNetworkService fetchNewsWithInfoType:eMPInfoTypeP2P page:self.loadMorePageInt++ onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        [self.tableView.infiniteScrollingView stopAnimating];
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        
        NSArray* infoArray = (NSArray *)info;
        if (infoArray.count <= 0) {
            self.tableView.showsInfiniteScrolling = NO;
            return;
        }
        for (NSDictionary* infoDic in infoArray) {
            MPNewsTableItem* item = [MPNewsTableItem itemWithInfoDic:infoDic];
            [self.firstSectionObject.items addObject:item];
        }
        [self.tableView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - property
- (KDCycleBannerView *)bannerView
{
    if (!_bannerView) {
        _bannerView = [[KDCycleBannerView alloc] init];
        _bannerView.delegate = self;
        _bannerView.datasource = self;
        _bannerView.continuous = YES;
        _bannerView.autoPlayTimeInterval = 5.0f;
    }
    return _bannerView;
}

- (NSMutableArray *)bannerItemArray
{
    if (!_bannerItemArray) {
        _bannerItemArray = [NSMutableArray array];
    }
    return _bannerItemArray;
}

#pragma mark - protocol
// 注册cell的类型，子类实现
- (void)registerCellClass
{
    NSString* path = [[NSBundle mainBundle] pathForResource:[MPNewsTableCell className] ofType:@"nib"];
    if ([NSString stringIsEmpty:path]) {
        [self.tableView registerClass:[MPNewsTableCell class] forCellReuseIdentifier:[MPNewsTableCell className]];
    }
    else
    {
        UINib* nib = [UINib nibWithNibName:[MPNewsTableCell className] bundle:nil];
        [self.tableView registerNib:nib forCellReuseIdentifier:[MPNewsTableCell className]];
    }
}

// 从object获取cell的类名
- (Class)cellClassByObject:(id)object
{
    if ([object isKindOfClass:[MPNewsTableItem class]]) {
        return [MPNewsTableCell class];
    }
    return nil;
}

- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MPNewsTableItem* item = [self objectAtIndexPath:indexPath];
        MPWebViewController* vc = [[MPWebViewController alloc] initWithTitle:item.newsTitle url:item.sourceUrl];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - bannerView dataSource
- (NSArray *)numberOfKDCycleBannerView:(KDCycleBannerView *)bannerView
{
    NSMutableArray* urlArray = [NSMutableArray array];
    for (MPNewsBannerItem* item in self.bannerItemArray) {
        [urlArray addObject:item.imageUrl];
    }
    return urlArray;
}

- (UIViewContentMode)contentModeForImageIndex:(NSUInteger)index
{
    return UIViewContentModeScaleToFill;
}

//- (UIImage *)placeHolderImageOfZeroBannerView
//{
//    return [UIImage imageFromColor:[UIColor blueColor]];
//}

//- (UIImage *)placeHolderImageOfBannerView:(KDCycleBannerView *)bannerView atIndex:(NSUInteger)index
//{
//    
//}

#pragma mark - bannerView delegate
- (void)cycleBannerView:(KDCycleBannerView *)bannerView didSelectedAtIndex:(NSUInteger)index
{
    KDLogTrace();
    MPNewsBannerItem* item = [self.bannerItemArray objectAtIndex:index];
    MPWebViewController* vc = [[MPWebViewController alloc] initWithTitle:[item.listId stringValue] url:item.sourceUrl];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
